package com.jsgt.greekfire.ui.mine.user.securityset.verifyphone

import android.os.CountDownTimer
import android.text.TextUtils
import androidx.lifecycle.Observer
import androidx.lifecycle.ViewModelProvider
import com.fhx.core.base.BaseActivity
import com.fhx.core.goToActivity
import com.fhx.core.utils.ToastUtils
import com.jsgt.greekfire.R
import com.jsgt.greekfire.bean.UserBean
import com.jsgt.greekfire.factory.UserViewModelFactory
import com.jsgt.greekfire.ui.mine.user.securityset.bindphone.BindPhoneActivity
import com.jsgt.greekfire.viewmodel.UserViewModel
import kotlinx.android.synthetic.main.activity_verify_phone.*

/**
 * 验证手机
 **/
class VerifyPhoneActivity : BaseActivity() {
    private val userViewModel: UserViewModel by lazy {
        ViewModelProvider(
            this,
            UserViewModelFactory()
        ).get(UserViewModel::class.java)
    }
    private var countDown: CountDownTimer? = null
    override fun getLayoutId(): Int = R.layout.activity_verify_phone
    override fun main() {
        title = getString(R.string.change_phone)
        bind_phone_tv.text = UserBean.instance.mobile
        confirm_tv.setOnClickListener {
            checkSmsCode()
        }
        send_code_tv.setOnClickListener {
            userViewModel.sendSMS(UserBean.instance.mobile!!)
        }
        userViewModel.sendSmsLiveData.observe(this, Observer {
            ToastUtils.show(this, "已发送")
            send_code_tv.isEnabled = false
            countDown = object : CountDownTimer(60000, 1000) {
                override fun onFinish() {
                    send_code_tv.isEnabled = true
                    send_code_tv.text = getString(R.string.send_sms_code)
                }

                override fun onTick(millisUntilFinished: Long) {
                    //加500是因为有时候不是特别准确，比如从6000直接跳到了4912
                    send_code_tv.text = "${(millisUntilFinished+500) / 1000}${getString(R.string.second)}"

                }
            }
            countDown?.start()
        })
        userViewModel.checkSMSLiveData.observe(this, Observer {
            goToActivity<BindPhoneActivity>()
            finish()
        })
        userViewModel.errorLiveData.observe(this, Observer {
            showProgress(false)
        })
    }

    private fun checkSmsCode() {
        val code = bind_phone_code_et.text.toString().trim()
        if (TextUtils.isEmpty(code)) {
            ToastUtils.show(this, "请输入验证码")
            return
        }
        showProgress(true)
        userViewModel.checkSMSCode(UserBean.instance.mobile!!, code)
    }

    override fun onDestroy() {
        super.onDestroy()
        countDown?.cancel()
        countDown = null
    }
}